import React, { useEffect, useState } from 'react';
import { connect } from 'umi';
import { Form, Button } from 'antd';
import DrawerCondition from '@/components/DrawerCondition';
import FormCondition from '@/components/FormCondition';
import Tree from '../../../TreeList';
const RoleForm = (props) => {
  const { dispatch, visible = {}, onClose, handleCallback, loading } = props;
  const { show = false, details = {}, type = 'insert' } = visible;
  const { role = {}, accessList = [], roleList = [] } = details;
  const { subAccessIdList: accessIdList, id } = role;
  const [form] = Form.useForm();
  useEffect(() => {
    setHalfCheckedList([]);
    if (show && type === 'insert') {
      fetchData();
    } else {
      setTreeList(accessList);
      setSelectedKeys(accessIdList);
      setList(roleList);
    }
  }, [show]);
  const [list, setList] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [treeList, setTreeList] = useState({});
  const [halfCheckedList, setHalfCheckedList] = useState([]);
  const fetchData = () => {
    dispatch({
      type: 'system/fetchRoleDetail',
      payload: {
        action: 'insert',
      },
      callback: (e) => {
        const { roleList, accessList } = e;
        setList(roleList);
        setTreeList(accessList);
      },
    });
  };
  // 递归函数，找到指定id的所有父id
  function findParentIds(data, childId, parentIds = []) {
    for (let item of data) {
      if (item.id === childId) {
        parentIds.push(item.pid);
        if (item.parentId) {
          findParentIds(data, item.id, parentIds);
        }
      } else if (item.subRoleDetailAccessList && item.subRoleDetailAccessList.length > 0) {
        findParentIds(item.subRoleDetailAccessList, childId, parentIds);
      }
    }
    return parentIds;
  }

  // 找出只有id的数组的父级，并整个数组去重
  function findAndFilterParentIds(data, idArray) {
    let parentIds = [];
    idArray.forEach(id => {
      const parents = findParentIds(data, id);
      parentIds = parentIds.concat(parents);
    });
    return [...new Set(parentIds)];
  }

  const fakeInsertAuthRole = () => {
    form.validateFields().then((values) => {
      dispatch({
        type:
          type === 'insert'
            ? 'system/fakeInsertAuthRole'
            : 'system/fakeUpdateAuthRole',
        payload: {
          id,
          ...values,
          accessIdList: [...selectedKeys, ...findAndFilterParentIds(treeList, selectedKeys), ...findAndFilterParentIds(treeList, findAndFilterParentIds(treeList, selectedKeys))],
        },
        callback: () => {
          onClose();
          handleCallback();
        },
      });
    });
  };
  const formItems = [
    {
      label: '角色名称',
      name: 'roleName',
    },
    {
      label: '角色描述',
      name: 'remark',
      rules: [{ required: false }],
    },
    {
      label: '选中角色',
      name: 'selectInfo',
      placeholder: '选中角色后会给当前角色附上默认菜单',
      type: 'select',
      select: list,
      rules: [{ required: false }],
      fieldNames: {
        label: 'roleName',
        value: 'id',
      },
      onChange: (e, record) => {
        const { option } = record;
        const { accessIdList = [], subAccessIdList = [] } = option;
        setHalfCheckedList(filterList(accessIdList, subAccessIdList));
        setSelectedKeys(subAccessIdList);
      },
    },
    {
      type: 'noForm',
      // rules: [{ required: false }],
      formItem: (
        <Tree
          onCheck={(e, o) => {
            const { halfCheckedKeys } = o;
            console.log(halfCheckedKeys, '选中的元素')
            setSelectedKeys(e);
            setHalfCheckedList(halfCheckedKeys);
          }}
          hasCard={true}
          selectedKeys={selectedKeys}
          list={treeList}
        ></Tree>
      ),
    },
  ];
  let filterList = (list, newList) => {
    const flag = (val) => {
      let falg = false;
      newList.forEach((o) => {
        if (o === val) {
          falg = true;
        }
      });
      return falg;
    };
    return list.reduce((item, val) => {
      if (!flag(val)) {
        return [...item, val];
      } else {
        return item;
      }
    }, []);
  };
  const modalProps = {
    title: type === 'insert' ? '新增' : '编辑',
    visible: show,
    onClose,
    footer: (
      <Button type="primary" loading={loading} onClick={fakeInsertAuthRole}>
        确定
      </Button>
    ),
  };
  return (
    <DrawerCondition {...modalProps}>
      <FormCondition form={form} formItems={formItems} initialValues={role}></FormCondition>
    </DrawerCondition>
  );
};
export default connect(({ loading }) => ({
  loading: loading.models.system,
}))(RoleForm);
